import moment from 'moment';
import { _ } from 'meteor/underscore';
import { findUser } from '/imports/models/Users';
import { Messages } from '/imports/models/Messages';

let formerLimit = null;
let formerTimestamp = null;
let formerChatContentHeight = null;

Template.messages_chatroom.onCreated(function () {
  Session.set('class.messages.renderedItemSum', 0);

  this.friend = new ReactiveVar();
  this.limit = new ReactiveVar(15);
  this.openNotice = new ReactiveVar(false);

  this.autorun(() => {
    this.friendId = Session.get('class.messages.chatroomFriendId');
    this.friend.set(findUser(this.friendId));
  });

  this.autorun(() => {
    this.resultSub = this.subscribe('get.messages', { friend_id: this.friendId }, this.limit.get());

    this.total = Counts.get('get.messages.counts');
  });
});

Template.messages_chatroom.onRendered(function () {
  let ps = new PerfectScrollbar('#messages-chatroom-ps');
  let viewport = this.$('#messages-chatroom-ps');
  let viewportHeight = viewport.height();

  this.autorun(() => {
    let sum = Session.get('class.messages.renderedItemSum');

    if (sum) {
      let chatContentHeight = this.$('#messages-chat-content').height() + 32;
      viewport.scrollTop(Math.round(chatContentHeight));

      if (formerLimit && this.limit.get() != formerLimit) {
        viewport.scrollTop(Math.round(chatContentHeight - formerChatContentHeight));
      }
    }
  });

  viewport.on('ps-y-reach-start', _.throttle(() => {
    formerChatContentHeight = this.$('#messages-chat-content').height();

    let lmt = this.limit.get();
    formerLimit = lmt;

    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.messages_chatroom.onDestroyed(function () {
  formerLimit = null;
  formerTimestamp = null;
  formerChatContentHeight = null;
});

Template.messages_chatroom.helpers({
  friendUsername: function () {
    let friend = Template.instance().friend.get();
    if (friend && friend.username) {
      return friend.username;
    }
    return '';
  },

  friendDisplay: function () {
    let friend = Template.instance().friend.get();
    if (friend && friend.profile && friend.profile.name) {
      return friend.profile.name;
    }
    if (friend && friend.emails) {
      return friend.emails[0].address;
    }
    return '';
  },

  friendAvatar: function () {
    let friend = Template.instance().friend.get();
    if (friend && friend.profile && friend.profile.avatar) {
      return friend.profile.avatar;
    }
    return '';
  },

  results: function () {
    const results = [];
    const array = Messages.find({}, {
      limit: Template.instance().limit.get(),
      sort: {
        createdAt: 1
      }
    }).fetch().reverse();

    array.forEach((item, index) => {
      let thisTimestamp = moment(item.createdAt).unix();

      if (!formerTimestamp) {
        formerTimestamp = thisTimestamp;
      }

      let range = formerTimestamp - thisTimestamp;

      if (index === 0) {
        range = 300;
      }

      if (range >= 300) {
        formerTimestamp = thisTimestamp;
        item.showTime = true;
      }

      results.unshift(item);
    });

    return results;
  },

  loading: function () {
    return !Template.instance().resultSub.ready();
  }
});

Template.messages_chatroom.events({
  'click .delete-messages' (e, instance) {
    Session.set('class.messages.messagesNotice.open', true);
    Session.set('class.messages.messagesNotice.type', 'delete-messages');
  },

  'click .go-homepage' (e, instance) {
    e.preventDefault();
    Router.go(`/u/${instance.friendId}`);
    $('#message-modal').modal('hide');
  }
});